<?php
namespace App\Policies\Admin;

use App\Models\AdminUser;
use App\Models\Config;
use App\Models\DyDwXref;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class AdminPolicy
{
    public $model;
    protected $admin_user;
    protected $xref_exists = false;
    protected $is_super_manger;
    protected $end_time;
    public function __construct(Model $model = null, AdminUser $admin_user = null)
    {
        $this->model = $model;
        $this->admin_user = $admin_user;
        $this->is_super_manger = $admin_user->isSuperManger();
        $config = Config::query()->where('key', 'dy_end')->select('key', 'value')->first();
        $this->end_time = $config ? $config->value : '2023-12-18 23:00:00';
    }

    public function over_can_edit()
    {
        return in_array($this->admin_user->gid, ['3201402268', '3201603816', 'test001']);
    }

    public function view_all()
    {
        return $this->is_super_manger;
    }

    public function can_delete()
    {
        if(is_object($this->model)){
            $con1 = $this->admin_user->can($this->model->getTable());
        }else{
            $con1 = false;
        }
        if ($this->over_can_edit()) {
            return true;
        }
        if (!$this->is_super_manger) {
            return $con1 && $this->model->dwdm == $this->admin_user->dwdm;
        }
        return $con1;
    }

    public function can_create()
    {
        if ($this->is_super_manger) {
            return false;
        }
        return $this->can_operate();
    }

    public function can_edit()
    {
        if(is_object($this->model)){
            $con1 = $this->admin_user->can($this->model->getTable());
        }else{
            $con1 = false;
        }
        if ($this->over_can_edit()) {
            return true;
        }
        if (!$this->is_super_manger) {
            return $con1 && $this->admin_user->dwdm == $this->model->dwdm;
        }
        return $con1;
    }

    public function can_operate()
    {
        if ($this->over_can_edit()) {
            return true;
        }
        return now()->toDateString() <= $this->end_time;
    }

    public function can_import()
    {
        # 总管理员不可以导入
        if ($this->is_super_manger) {
            // return false;
        }
        return now()->toDateTimeString() <= $this->end_time;
    }

    public function can_create_base()
    {
        return now()->toDateTimeString() <= $this->end_time;
    }
    
    public static function make(...$params)
    {
        return new static(...$params);
    }
}